
import { randomUUID } from 'crypto';
import express from 'express';
import fs from 'fs';
import path from 'path';
import * as readline from 'readline';
import { scheduleJob } from 'node-schedule';
import fetch from 'node-fetch';
var app = express();

import { fileURLToPath } from 'url';

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

function ask(question) {
    return new Promise(resolve => {
        rl.question(question, input => resolve(input));
    });
}

const __dirname = path.dirname(fileURLToPath(import.meta.url));

app.use(function (req, res, next) {
    var data = '';
    req.setEncoding('utf8');
    req.on('data', function (chunk) {
        data += chunk;
    });
    req.on('end', function () {
        try {
            req.body = JSON.parse(data);
        } catch (error) {
            req.body = data;
        }
        next();
    });
})

app.post('*', function (req, res) {
    console.log("发起请求")
    const info = req.body
    infos[info.user] = info
    // console.log(infos)
    // console.log(commands)

    if (commands[info.user]) {
        console.log({ command: commands[info.user], id: randomUUID() })
        res.send(JSON.stringify({command: commands[info.user], id: randomUUID()}));
        delete commands[info.user]
    } else {
        res.send("{}");
    }
})


app.get('/setcom', function (req, res){
    // console.clear()
    console.log(infos)
    console.log(commands)
    var command = req.query.cmd
    console.log(Object.keys(infos).map(name => `${name}${infos[name].onlineState === 1 ? "(离线)" : ""} 当前服务器:${infos[name].gameId || "无"} 状态:${infos[name].state}`).join("\n"))
    if (command.split(/\s+/)[0].toLowerCase() === "join") {
        let gameId = command.split(/\s+/)[1]
        if (!+gameId) return
        joinGame(gameId, Object.keys(infos))
    }
    if (command.split(/\s+/)[0].toLowerCase() === "leave") {
        leaveGame(Object.keys(infos))
    }
    if (command.split(/\s+/)[0].toLowerCase() === "connect") {
        connectGame(Object.keys(infos).filter(name => infos[name].onlineState === 1))
    }
    console.log(infos)
    console.log(commands)
    res.send("ok")
})

app.listen(80, function () {
})

const infos = {}
const commands = {}

async function joinGame(gameId, accounts) {
    console.log("已加入服务器")
    accounts.forEach(name => {
        commands[name] = `join ${gameId}`
    });
};

async function connectGame(accounts) {
    console.log("已重连服务器")

    accounts.forEach(name => {
        commands[name] = `connect`
    });
};

async function leaveGame(accounts) {
    console.log("已退出服务器")

    accounts.forEach(name => {
        const info = infos[name] || null
        if (!info || !info.gameId) return
        fetchBF1Api("Game.leaveGame", info.sessionId, { gameId: info.gameId })
    });
};

async function fetchBF1Api(method, sessionId, params = {}) {
    const baseUrl = "https://sparta-gw.battlelog.com/jsonrpc/pc/api"
    params.game = "tunguska"
    const body = {
        "jsonrpc": "2.0",
        "method": method,
        "params": params,
        "id": 1,
    }
    const init = {
        body: JSON.stringify(body),
        method: "POST",
        headers: {
            "content-type": "application/json"
        },
    }
    if (sessionId) { init.headers["X-GatewaySession"] = sessionId }

    const response = await fetch(baseUrl, init)
    const result = await response.json()

    if (result.error) {
        throw new Error("请求错误")
    }

    return result.result
}

scheduleJob('* * * * * *', (time) => {
    Object.keys(infos).map(i => infos[i]).forEach(info => {
        const now = new Date().getTime()
        if (now - info.time >= 5000 && info.state === "Loading") {
            info.state = "Playing"
        }
        if (now - info.time >= 7200 * 1000) {
            delete infos[info.name]
        }
    })
});

// (async () => {
//     console.clear()
//     while (true) {
//         // console.clear()
//         console.log(Object.keys(infos).map(name => `${name}${infos[name].onlineState === 1 ? "(离线)" : ""} 当前服务器:${infos[name].gameId || "无"} 状态:${infos[name].state}`).join("\n"))
//         const command = await ask("> ")
//         if (command.split(/\s+/)[0].toLowerCase() === "join") {
//             let gameId = command.split(/\s+/)[1]
//             if (!+gameId) return
//             await joinGame(gameId, Object.keys(infos))
//         }
//         if (command.split(/\s+/)[0].toLowerCase() === "leave") {
//             await leaveGame(Object.keys(infos))
//         }
//         if (command.split(/\s+/)[0].toLowerCase() === "connect") {
//             await connectGame(Object.keys(infos).filter(name => infos[name].onlineState === 1))
//         }
//     }
// })();